from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpRequest
from django.views.decorators.csrf import csrf_exempt  # 导入csrf免检装饰器

from regist.models import UserInfo


# Create your views here.


def test(request):
    '''test'''
    return HttpResponse('ok')


def registPage(req):
    '''注册用户的页面'''

    return HttpResponse(render(req, 'registTemplates/regist.html'))


@csrf_exempt  # 装饰器, 开启csrf免检
def registAction(req):
    '''注册信息提交_ajax'''


    # 判断是get 还是 post
    if req.method == 'GET':
        return JsonResponse({"regist":'0'})
        pass
    elif req.method == 'POST':

        # 获取用户提交的注册信息
        queryDic = req.POST
        userName = queryDic['userName']
        phoneNo = queryDic['phoneNo']
        password = queryDic['password']
        nick = queryDic['nick']

        # 写入mysql
        user = UserInfo()
        user.userName = userName
        user.password = password
        user.phoneNum = phoneNo
        user.nickName = nick
        user.save()

        userCheck = UserInfo.objects.get(userName=userName)
        # 写入成功
        if userCheck.userName == userName:
            """已存入mysql"""
            return JsonResponse({"regist": '1'})
        # 写入失败
        else:
            """未存入mysql"""
            return JsonResponse({"regist": '0'})
